﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;


namespace Xceed.Silverlight.DataGrid.Export
{
  public class TextExporter : ExporterBase
  {
    protected TextExporter( DataGridControl dataGridControl )
      : base( dataGridControl )
    {
    }

    public string ExportToText( IList<SelectionRange> selectedRanges )
    {
      Stream stream = new MemoryStream();

      // Call the synchronous method, so the items can be pasted to the clipboard within a user-initiated event, thus without an exception.
      this.Export( stream, selectedRanges );

      string text = this.ConvertStreamToText( stream );

      stream.Close();
      stream.Dispose();

      return text;
    }

    private string ConvertStreamToText( Stream stream )
    {
      string copyText = "";
      Encoding encoding = this.GetCurrentEncoding();
      byte[] buffer = new byte[ 32768 ];
      int bytesRead = 0;
      stream.Position = 0;

      // Get the content of the exported stream as a string.
      while( ( bytesRead = stream.Read( buffer, 0, buffer.Length ) ) > 0 )
      {
        copyText += encoding.GetString( buffer, 0, bytesRead );
      }

      return copyText;
    }

    internal virtual Encoding GetCurrentEncoding()
    {
      return Encoding.Unicode;
    }
  }
}
